/*
Copyright 2010,2011 Matt Van Der Westhuizen

This file is part of CGLL.

CGLL is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

CGLL is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with CGLL.  If not, see <http://www.gnu.org/licenses/>.
*/

package org.chaoticengine.cgll.collision;

import java.util.LinkedList;
import java.util.List;
import org.chaoticengine.cgll.entity.Entity;

/**
 * Simple broad-phase hit detector that checks for hits between all entities on
 * the screen. This should allow for initial testing of hit-detection and can be
 * replaced with a more advanced broad phase at a later stage once levels become
 * complex enough for performance to become an issue.
 *
 * @author Matt v.d. Westhuizen
 */
public class SimpleBroadPhaseCollisionDetector implements IBroadPhaseCollisionDetector {
    protected INarrowPhaseCollisionDetector narrowPhase = null;
    protected List<Entity> entities = null;

    public SimpleBroadPhaseCollisionDetector(INarrowPhaseCollisionDetector npCd) {
        entities = new LinkedList<Entity>();
        this.narrowPhase = npCd;
    }

    public void addEntity(Entity entity) {
        entities.add(entity);
    }

    public void addEntities(List<Entity> entities) {
        entities.addAll(entities);
    }

    public void removeEntity(Entity e) {
        entities.remove(e);
    }

    public void doHitDetection() {
        for (int i = 0; i < entities.size(); i++) {
            Entity e1 = entities.get(i);

            for (int j = i + 1; j < entities.size(); j++) {
                Entity e2 = entities.get(j);

                if (narrowPhase.isHit(e1, e2)) {
                    e1.getComponentManager().handleCollision(e2);
                    e2.getComponentManager().handleCollision(e1);
                }
            }
        }
    }

    public INarrowPhaseCollisionDetector getNarrowPhaseHitDetector() {
        return(narrowPhase);
    }

    public void setNarrowPhaseHitDetector(INarrowPhaseCollisionDetector npHd) {
        if (npHd != null) {
            this.narrowPhase = npHd;
        }
    }
}
